<?php

namespace app\organization\controller;

use app\common\controller\Frontend;
use app\common\enums\LevelTypeEnum;
use app\common\model\banxi\core\CoreAccountClassHour;
use app\common\model\banxi\learn\LearnSkRecord;
use app\common\model\banxi\organization\Organization;
use app\common\model\banxi\organization\OrganizationLevelConfig;
use app\common\model\banxi\student\Student;
use app\common\model\banxi\trainer\Trainer;
use app\common\service\organization\OrganizationLevelService;
use app\common\service\PosterService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;

/**
 * 首页
 */
class Personal extends Frontend
{
    protected array $noNeedLogin = [];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }


    /**
     * 查询-首页统计
     */
    public function homeTjData()
    {
        $user = $this->auth->getUser();
        $organizationId = $user['organizationId'];
        $organizationModel = new Organization();
        $organizationInfo = $organizationModel->with([
            'organizationBaseInfo' => function ($query) {
                $query->field('id,name,managerName');
            }, 'inviteInfo' => function ($query) {
                $query->field('id,name,managerName');
            }, 'accompanyInfo' => function ($query) {
                $query->field('id,name,managerName');
            }, 'levelInfo' => function ($query) {
                $query->field('id,levelType,name');
            }
        ])->where('id', $organizationId)->field('id,code,parentId,inviteId,accompanyId,level')->find();
        //所属机构
        if ($organizationInfo['parentId'] == 0) {
            $parentName = $organizationModel->getOrganizationInfo()['name'];
        } else {
            $parentName = isset($organizationInfo['organizationBaseInfo']['name']) ? $organizationInfo['organizationBaseInfo']['name'] : '';
        }
        //邀请人
        $inviteName = isset($organizationInfo['inviteInfo']['name']) ? $organizationInfo['inviteInfo']['name'] : '';
        //陪跑员
        $accompanyName = isset($organizationInfo['accompanyInfo']['name']) ? $organizationInfo['accompanyInfo']['name'] : '';
        //等级
        $levelName = '';
        //升级条件
        $upLevelProgress = 0;
        $levelType = 0;
        $needUpLevel = false;
        if (!empty($organizationInfo['levelInfo'])) {
            $levelId = $organizationInfo['levelInfo']['id'];
            $levelName = $organizationInfo['levelInfo']['name'];
            $levelType = $organizationInfo['levelInfo']['levelType'];
            $organizationLevelService = new OrganizationLevelService();
            $organizationLevelConfigModel = new OrganizationLevelConfig();
            $nextLevel = $organizationLevelConfigModel->getNextLevel($levelId, $levelType);
            $needUpLevel = !empty($nextLevel);//是否需要升级
            if ($needUpLevel) {
                if ($levelType == LevelTypeEnum::E1) {
                    //自营校区+直推校区
                    $upLevelProgress = $organizationLevelService->campusUpgradeStatistics($organizationId);
                }
                if ($levelType == LevelTypeEnum::E2) {
                    $studentBuyClassMinute = $organizationLevelService->partnerUpgradeStatistics($organizationId);
                    foreach ($studentBuyClassMinute as $buyClass) {
                        if ($buyClass >= $nextLevel['requireClass']) {
                            $upLevelProgress++;
                        }
                    }

                }
            }
        }
        //编码
        $orgCode = $organizationInfo['code'];
        $classHour = CoreAccountClassHour::where('organizationId', $user['organizationId'])->field('class30Minute,class60Minute')->find();
        $minute30Num = $classHour['class30Minute'] ?? 0;
        $minute60Num = $classHour['class60Minute'] ?? 0;
        $orgHour = $minute30Num + $minute60Num;
        $trainerIds = Trainer::where('organizationId', $user['organizationId'])->column('id');
        $trainerTotalLearn = '0.00';
        if (!empty($trainerIds)) {
            $sumLearnMinutes = LearnSkRecord::where([
                ['trainerId', 'in', $trainerIds],
                ['isEnd', '=', 1]
            ])->sum('learnMinutes');
            $trainerTotalLearn = bcdiv($sumLearnMinutes, 60, 2);
        }
        $studentNum = Student::where('organizationId', $user['organizationId'])->count('id');
        $orgNum = Organization::where('parentId', $user['organizationId'])->count('id');
        $trainerNum = Trainer::where('organizationId', $user['organizationId'])->count('id');
        $returnList = [
            'parentName' => $parentName,
            'inviteName' => $inviteName,
            'accompanyName' => $accompanyName,
            'levelType' => $levelType,
            'upLevelProgress' => $upLevelProgress,
            'needUpLevel' => $needUpLevel,
            'levelName' => $levelName,
            'orgCode' => $orgCode,
            'orgHour' => $orgHour,
            'minute30Num' => $minute30Num,
            'minute60Num' => $minute60Num,
            'studentNum' => $studentNum,
            'orgNum' => $orgNum,
            'trainerNum' => $trainerNum,
            'trainerTotalLearn' => $trainerTotalLearn
        ];
        $this->ok(__('Operation completed'), $returnList);

    }

    /**
     * 查询-海报
     * @return void
     */
    public
    function posterImage(): void
    {
        $user = $this->auth->getUser();
        $pictureService = new PosterService();
        try {
            $res = $pictureService->createPoster($user['organizationId'], $user['id']);
            if (!$res) {
                throw new ValidateException($pictureService->getError());
            }
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            $this->fail($pictureService->getError());
        }
        $this->ok('ok', $res);
    }
}